package com.cws4cloud.cws.sdAdmin.biz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.cws4cloud.cws.admin.api.dto.MenuTree;
import com.cws4cloud.cws.common.core.constant.CommonConstants;
import com.cws4cloud.cws.common.core.constant.enums.MenuTypeEnum;
import com.cws4cloud.cws.common.core.exception.CheckedException;
import com.cws4cloud.cws.common.core.util.TreeUtil;
import com.cws4cloud.cws.sdAdmin.api.dto.ParamTree;
import com.cws4cloud.cws.sdAdmin.api.dto.WebsiteTree;
import com.cws4cloud.cws.sdAdmin.biz.mapper.ParamMapper;
import com.cws4cloud.cws.sdAdmin.api.entity.Param;
import com.cws4cloud.cws.sdAdmin.api.service.ParamService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author zhulj
 * @date 2021-05-06 15:10:12
 */
@Service
@RequiredArgsConstructor
public class ParamServiceImpl extends ServiceImpl<ParamMapper, Param> implements ParamService {

	private final ParamMapper paramMapper;

	@Override
	public List<ParamTree> listParamTrees(boolean lazy, Integer parentId, String name) {
		if (lazy){
			return getParamTree(paramMapper.listParamTree(parentId,name),parentId);
		} else {
			return getParamTree(paramMapper.listParamTree(null,name),-1);
		}
	}

	@Override
	public Boolean saveParam(Param param) {
		if (paramMapper.selectCount(new QueryWrapper<Param>().lambda().eq(Param::getValue,param.getValue()))>0){
			throw new CheckedException("参数值已存在，不能重复!!!");
		}
		return SqlHelper.retBool(paramMapper.insert(param));
	}

	@Override
	public List<Param> listByParent(Integer parentId, String parentValue) {
		QueryWrapper<Param> queryWrapper = new QueryWrapper<Param>();
		if (parentId!=null){
			queryWrapper.lambda().eq(Param::getParentId,parentId);
			return paramMapper.selectList(queryWrapper);
		} else {
			if (StrUtil.isNotBlank(parentValue)){
				queryWrapper.lambda().eq(Param::getValue,parentValue);
				Param parentParam = paramMapper.selectOne(queryWrapper);
				if (parentParam!=null){
					return paramMapper.selectList(new QueryWrapper<Param>().lambda().eq(Param::getParentId,parentParam.getId()));
				}
			}
		}
		return null;
	}

	private List<ParamTree> getParamTree(List<ParamTree> params, Integer parentId) {
		return TreeUtil.build(params, parentId);
	}
}
